package com.kwan.x_im.data.http;


import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.kwan.x_im.data.AppRepository;
import com.kwan.xframe.mvvm.BaseTokenManager;
import com.kwan.xframe.mvvm.data.source.http.HttpResult;

import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;

import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.functions.Function;
import timber.log.Timber;

public class HttpTokenManager extends BaseTokenManager {

	public static volatile HttpTokenManager instance = null;

	public static HttpTokenManager getInstance() {
		if (instance == null) {
			synchronized (HttpTokenManager.class) {
				if (instance == null) {
					instance = new HttpTokenManager();
				}
			}
		}
		return instance;
	}

	private HttpTokenManager() {
		super();
	}


	/**
	 * 获取 token
	 */
	@Override
	public Observable<String> fetchTokenObservable() {
		return AppRepository.getInstance().refreshToken().flatMap(new Function<HttpResult<Object>, Publisher<String>>() {
			@Override
			public Publisher<String> apply(HttpResult<Object> result) throws Throwable {
				return new Flowable<String>() {
					@Override
					protected void subscribeActual(@io.reactivex.rxjava3.annotations.NonNull Subscriber<? super String> subscriber) {
						Timber.e("refreshToken subscribeActual...");
						JsonElement parser = JsonParser.parseString(result.getData().toString());
						String token = parser.getAsJsonObject().get("token").getAsString();
						subscriber.onNext(token);
						subscriber.onComplete();
					}
				};
			}
		}).toObservable();
	}

	@Override
	public void onFreshToken(String token) {
		//http header
		Timber.e("onFreshToken:" + token);
//		if (LoginActivity.account != null)
//			SPUtils.getInstance(LoginActivity.account.getId()).put("token", token);
//		AppRepository.getInstance().mHttpDataSource.refreshToken(token, HttpDataSource.API_URL);
	}
}
